﻿using B.X.Rabbit.Domain.RBAC;
using B.X.Rabbit.Infrastructure.IReponsitory;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace B.X.Rabbit.Infrastructure.Reponsitory
{
    public class UserRepository : BaseReponsitory<User>, IUserRepository
    {
        private readonly MainDbContext _context;
        private readonly ILogger<BaseReponsitory<User>> _logger;
        public UserRepository(MainDbContext context, ILogger<BaseReponsitory<User>> logger) : base(context, logger)
        {
            this._context = context;
            this._logger = logger;
        }

        /// <summary>
        /// 事务添加用户角色
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="roleIds"></param>
        /// <returns></returns>

        public async Task<bool> UserRoleInsert(User userInfo, int[] roleIds)
        {
            try
            {
                var res = false;
                var spconce = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                try
                {
                    //添加用户
                    var userid = await _context.Users.AddAsync(userInfo);
                    await _context.SaveChangesAsync();
                    //添加用户角色
                    foreach (var rid in roleIds)
                    {
                        await _context.UserRoles.AddAsync(new UserRole
                        {
                            UserId = userid.Entity.UserId,
                            RoleId = rid
                        });
                    }
                    await _context.SaveChangesAsync();
                    //提交事务
                    spconce.Complete();
                    res = true;
                    return res;
                }
                finally
                {
                    //回滚事务
                    spconce.Dispose();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "事务添加用户角色失败");
                return false;
            }
        }

    }
}
